#include "testwebmap.h"
#include "ui_testwebmap.h"

#include <QDebug>
#include <QFileInfo>
#include <QWebFrame>
#include <QMessageBox>

testWebMap::testWebMap(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::testWebMap)
{
    ui->setupUi(this);
    QFileInfo xmlinfo("./test.html");

    connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
                this, SLOT(addObjectToJs()));

    ui->webView->load(QUrl::fromLocalFile(xmlinfo.absoluteFilePath()));

    m_pTcpServer = new QTcpServer(this);
    m_pTcpClient = new QTcpSocket(this);
    connect(m_pTcpServer,SIGNAL(newConnection()),this,SLOT(acceptDevConnect()));
    connect(ui->about, SIGNAL(triggered()), this, SLOT(about()));

    bSvrStart = false;
    bClientVaild = false;

}

testWebMap::~testWebMap()
{
    delete ui;
}

//接收远端设备的新连接
void testWebMap::acceptDevConnect()
{
    if(bClientVaild)
    {
        qDebug()<<"tcpclient already valid ";
        return;
    }

    qDebug()<<"recv dev new tcp connection ";

    m_pTcpClient = m_pTcpServer->nextPendingConnection();

    connect(m_pTcpClient, SIGNAL(readyRead()), this, SLOT(onDataRecv()));
    connect(m_pTcpClient, SIGNAL(disconnected()), this, SLOT(disConnectEvent()));
    bClientVaild = true;
}

void testWebMap::convertGpsData(QString srcData, QString &destData,int pos)
{
    int dotPos = srcData.indexOf(".");
    QString min=srcData.right(srcData.size()-(dotPos-2));
    double fMin = min.toFloat();
    double fD = (double)(srcData.left(pos).toInt()+(fMin/60));
    destData = QString("%1").arg(QString::number(fD, 'f', 9)); //取到小数点后9位

    qDebug()<<"min: "<<(fMin/60)<<",fD: "<<fD;
}

//接收数据并返回数据
void testWebMap::onDataRecv()
{
    QString longitude;
    QString latitude;
    while (m_pTcpClient->bytesAvailable()>0)
    {
        QByteArray datagram;

        datagram.resize(m_pTcpClient->bytesAvailable());
        datagram = m_pTcpClient->readLine();

        QString gpsStr=datagram.data();
        if (std::string::npos == gpsStr.toStdString().find("RMC"))
        {
            qDebug()<<"not find RMC data";
            continue;
        }

        QStringList strList = gpsStr.split(",");
        if (strList.isEmpty() || (strList.size() < 3))
        {
            qDebug()<<"list is : "<<strList.isEmpty()<<", size = "<<strList.size();
            continue;
        }

        latitude = strList.at(3);
        longitude=strList.at(5);

        if(strList.at(2) == "V")
        {
            qDebug()<<"gps data invalid!";
            return;
        }

        convertGpsData(strList.at(3),latitude,2);
        convertGpsData(strList.at(5),longitude,3);

        QString fun=QString("doLocal(\"%1\",\"%2\");").arg(longitude).arg(latitude);

        qDebug()<<"fun: "<<fun ;

        ui->webView->page()->mainFrame()->evaluateJavaScript(fun);

    }
}

void testWebMap::disConnectEvent()
{
    bClientVaild = false;
    m_pTcpClient->close();
}

void testWebMap::addObjectToJs()
{
    ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("testWebMap", this);
}

void testWebMap::doJavascript2(QString str)
{
    ui->longitude->setText(str);
}

void testWebMap::on_modifyButton_clicked()
{
    QString longitude=ui->longitude->text();
    QString latitude=ui->latitude->text();

    convertGpsData(latitude,latitude,2);
    convertGpsData(longitude,longitude,3);

    QString fun=QString("doLocal(\"%1\",\"%2\");").arg(longitude).arg(latitude);

    qDebug()<<"longitude: "<<longitude<<", latitude: "<<latitude ;
    qDebug()<<"fun: "<<fun ;

    ui->webView->page()->mainFrame()->evaluateJavaScript(fun);
}


void testWebMap::on_svrButtn_clicked()
{
    if (!bSvrStart)
    {
        bSvrStart = true;
        quint16 svrPort = ui->port->text().toShort();
        qDebug()<<"port: "<<svrPort;
        m_pTcpServer->listen(QHostAddress::Any,svrPort);
        ui->svrButtn->setText(tr("关闭"));
    }
    else
    {
        bClientVaild = false;
        bSvrStart = false;
        m_pTcpServer->close();
        ui->svrButtn->setText(tr("启动"));
    }

}

void testWebMap::on_reloadUrl_clicked()
{
    ui->webView->reload();
}


void testWebMap::about()
{
    QMessageBox::about(this, "about", tr("调试服务器    \n"
                                         "Email   :  wuquan-1230@163.com\n"
                                         "Author  :  wuwei\n"
                                         "Ver      :  2018-01-28\n"
                                         "说 明    :  将gps原始经纬度数据显示在百度地图上，使用时需要联网；"
                                         ));
}
